import 'package:flutter/material.dart';
import 'package:situation/data/database/sql_provider.dart';
import 'package:situation/domain/db/user_latlon_domain.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

class Mymark extends StatefulWidget {
  const Mymark({super.key, required this.handleChange, required this.checkedIds});

  final Function(List<UserLatlonDomain>) handleChange;
  final List checkedIds;

  @override
  State<Mymark> createState() => _MymarkState();
}

class _MymarkState extends State<Mymark> {
  List list = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();
  }

  getData() async {
    // 查询所有
    List dataList = await SqlProvider.instance.query(
      UserLatlonDomain.tableName,
    );
    dataList.forEach((element) {
      var el = Map.unmodifiable(element);
      var mp = Map.from(el);
      if( widget.checkedIds.contains(mp['id'])){
        mp['checked'] = true;
      }else {
        mp['checked'] = false;
      }
      list.add(mp);
    });
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: list.length,
      itemBuilder: (c, index) {
        return ListTile(
          leading: Checkbox(
            value: list[index]['checked'],
            onChanged: (bool? e) {
              setState(() {
                list[index]['checked'] = e;
              });
              // 获取所有checked = true的
              var checkedList = list.where((element) => element['checked'] == true).toList();
              widget.handleChange(checkedList.map((e) => UserLatlonDomain.fromJson(e)).toList());

            },
          ),
          // 左侧图标
          title: Text('${list[index]['name']}'),
          // 标题
          subtitle: Text(
            '${list[index]['type'] == 'point'
                ? '点'
                : list[index]['type'] == 'line'
                ? '线'
                : '面'}',
          ),
          // 副标题
          trailing: IconButton(
            icon: const Icon(Icons.delete),
            onPressed: () {
              deleteIndex(index);
            }, // 触发删除操作
          ),
          onTap: () {
            // 点击事件处理
          },
        );
      },
    );
  }

  void deleteIndex(int index) {
    showGeneralDialog(
      context: context,
      pageBuilder: (
        BuildContext buildContext,
        Animation<double> animation,
        Animation<double> secondaryAnimation,
      ) {
        return TDAlertDialog(
          title: '确认删除么',
          rightBtnAction: () {
            Navigator.of(context).pop();
            setState(() {
              list.removeAt(index);
            });
            SqlProvider.instance.delete(
              UserLatlonDomain.tableName,
              " id = ? ",
              [list[index]['id']],
            );
          },
        );
      },
    );
  }
}
